#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<assert.h>

void writer(int wfd)
{
    const char* str = "我是子进程,o.O,我在给你发消息";
    char buffer[128];
    int cnt = 0;
    pid_t pid = getpid();
    while(1)
    {
        snprintf(buffer,sizeof(buffer),"message:%s,pid:%d,count:%d\n",str,pid,cnt);
        write(wfd, buffer, strlen(buffer));
        cnt++;
        sleep(1);
    }
    close(wfd);
}

void reader(int rfd)
{
    char buffer[1024];
    int cnt = 10;
    while(1)
    {
        size_t n = read(rfd,buffer,sizeof(buffer)-1);
        if(n>0)
            printf("父亲获得信息是: %s\n", buffer);
        else
        {
            printf("缓冲区读完了，文件也读完了\n");
            break;
        }
        cnt--;
        if(cnt==0)
            break;
    }
    close(rfd);
}


int main()
{
    //创建管道
    int pipefd[2];
    int n = pipe(pipefd);
    if(n<0)
        return 1;
    pid_t id = fork();

    if(id == 0)
    {
        //子进程  关掉读端，只写
        close(pipefd[0]);
        writer(pipefd[1]);
        exit(1);
    }

    //父进程
    //关掉写端，只读
    close(pipefd[1]);
    reader(pipefd[0]);
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if(rid == id)
        printf("退出码为:%d,信号为:%d\n",WEXITSTATUS(status), status & 0x7f);

    return 0;
}